<script setup lang='ts'>
import type { OptionsType, PlusColumn } from 'plus-pro-components'
import type { VxeGridProps } from 'vxe-table'

import { useOpen } from '@/pages/home/component/use-open'
import { useGetProductCategoryOptions, useGetProductPage, useOfflineProduct } from '@fl/api/man-api'
import { SearchForm, SearchTable } from '@fl/components'
import { useMessage } from '@fl/hooks/web/use-message'
import { treeFindLabel } from '@fl/utils/tree'
import { cloneDeep } from 'lodash-es'
import { useRouter } from 'vue-router'

import { PRODUCT_SOURCE, PRODUCT_STATUS, PRODUCT_STATUS_MAP, PRODUCT_TYPE } from './constant'

const { openNewWindow } = useOpen()
const { createConfirmModal } = useMessage()
const router = useRouter()

const initialState = {
    createTimeRange: [],
    productAuditTimeRange: [],
} as any
const state = ref(cloneDeep(initialState))

const searchConditions = ref(cloneDeep(initialState))
const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const getProductPageParams = computed(() => {
    return {
        ...searchConditions.value,
        page: tablePage.currentPage,
        size: tablePage.pageSize,
    }
})

const { data: productPageData, isLoading: isGetProductPageLoading, total: productTotal } = useGetProductPage(getProductPageParams)
const { data: productCategoryOptionsData, isLoading: isGetProductCategoryOptionsLoading } = useGetProductCategoryOptions()
const { isPending: isOfflineProductPending, mutate: offlineProduct } = useOfflineProduct()

// #region Form
const isFormLoading = computed(() => isGetProductCategoryOptionsLoading.value)

const columns: PlusColumn[] = [
    {
        colProps: {
            span: 8,
        },
        label: '产品状态',
        options: PRODUCT_STATUS,
        prop: 'productStatus',
        valueType: 'select',
    },
    {
        colProps: {
            span: 8,
        },
        label: '产品类目',
        options: productCategoryOptionsData as OptionsType,
        prop: 'productCategoryId',
        valueType: 'cascader',
    },
    {
        colProps: {
            span: 8,
        },
        label: '产品名称',
        prop: 'productName',
    },
    {
        colProps: {
            span: 8,
        },
        label: '产品编号',
        prop: 'productNo',
    },
    {
        colProps: {
            span: 8,
        },
        fieldProps: {
            endPlaceholder: '请选择结束日期',
            startPlaceholder: '请选择开始日期',
            type: 'daterange',
            valueFormat: 'YYYY-MM-DD',
        },
        label: '提交时间',
        prop: 'createTimeRange',
        valueType: 'date-picker',
    },
    {
        colProps: {
            span: 8,
        },
        fieldProps: {
            endPlaceholder: '请选择结束日期',
            startPlaceholder: '请选择开始日期',
            type: 'daterange',
            valueFormat: 'YYYY-MM-DD',
        },
        label: '上架审核时间',
        prop: 'productAuditTimeRange',
        valueType: 'date-picker',
    },
    {
        colProps: {
            span: 8,
        },
        label: '公司名称',
        prop: 'enterpriseName',
    },
    {
        colProps: {
            span: 8,
        },
        label: '产品型号',
        prop: 'productModel',
    },
    {
        colProps: {
            span: 8,
        },
        label: '产品类型',
        options: PRODUCT_TYPE,
        prop: 'productType',
        valueType: 'select',
    },
]

function search() {
    const inputState = cloneDeep(state.value)
    searchConditions.value = {
        ...inputState,
        createTimeEnd: inputState.createTimeRange?.[1],
        createTimeRange: undefined,
        createTimeStart: inputState.createTimeRange?.[0],
        productAuditTimeEnd: inputState.productAuditTimeRange?.[1],
        productAuditTimeRange: undefined,
        productAuditTimeStart: inputState.productAuditTimeRange?.[0],
        productCategoryId: inputState.productCategoryId?.length ? inputState.productCategoryId.slice(-1)[0] : '',
    }
    resetTablePage()
}

function reset() {
    state.value = cloneDeep(initialState)
    searchConditions.value = cloneDeep(initialState)
    resetTablePage()
}

function resetTablePage() {
    tablePage.currentPage = 1
    tablePage.pageSize = 10
}
// #endregion

// #region Table
const gridOptions = reactive<VxeGridProps>({
    columns: [
        { field: 'productNo', title: '产品编码', width: 240 },
        { field: 'productName', title: '产品名称', width: 240 },
        { field: 'brandName', title: '产品品牌', width: 180 },
        { field: 'categoryPath', title: '产品类目', width: 240 },
        { field: 'enterpriseName', title: '所属公司', width: 200 },
        { field: 'productModel', title: '产品型号', width: 160 },
        { field: 'productPrice', title: '价格', width: 200 },
        { field: 'productAgreementsCount', title: '相关协议', width: 100 },
        { field: 'productSource', formatter: formatProductSource, title: '来源', width: 160 },
        { field: 'createTime', title: '提交时间', width: 170 },
        { field: 'productAuditTime', title: '上架审核时间', width: 170 },
        { field: 'productStatus', fixed: 'right', formatter: formatProductStatus, title: '状态', width: 100 },
        { fixed: 'right', slots: { default: 'operate' }, title: '操作', width: 160 },
    ],
})

function formatProductSource({ cellValue }) {
    return treeFindLabel({ targetValue: cellValue, treeData: PRODUCT_SOURCE })
}

function formatProductStatus({ cellValue }) {
    return treeFindLabel({ targetValue: cellValue, treeData: PRODUCT_STATUS })
}

watchEffect(() => {
    tablePage.total = productTotal.value
})
// #endregion

// #region UI Listener
function onPreviewBtnClick(row: any) {
    openNewWindow('/product-info', {
        id: row.productNo,
    })
}

function onLogBtnClick(row: any) {
    router.push({ path: '/operations-pages/product-center/product-log', query: { id: row.id } })
}

function onOffShelfBtnClick(row: any) {
    createConfirmModal({
        content: '确定要下架该产品吗？',
        onSuccess: () => {
            offlineProduct(row.id, {
                onSuccess() {
                    ElMessage.success('操作成功')
                },
            })
        },
        title: '提示',
    })
}
// #endregion
</script>

<template>
    <el-skeleton v-if="isFormLoading"
                 animated
    />

    <SearchForm v-else
                v-model="state"
                :columns="columns"
                submit-text="查询"
                class="mb-20"
                :row-props="{ gutter: 40 }"
                @submit="search"
                @reset="reset"
    />

    <SearchTable v-bind="gridOptions"
                 v-model:pager="tablePage"
                 :data="productPageData"
                 :loading="isGetProductPageLoading"
    >
        <template #operate="{ row }">
            <el-button text
                       type="primary"
                       class="!p-4"
                       @click="onPreviewBtnClick(row)"
            >
                预览
            </el-button>

            <el-button text
                       type="primary"
                       class="!p-4"
                       @click="onLogBtnClick(row)"
            >
                日志
            </el-button>

            <el-button v-if="row.productStatus === PRODUCT_STATUS_MAP.ON_SHELF"
                       text
                       type="danger"
                       class="!p-4"
                       :loading="isOfflineProductPending"
                       @click="onOffShelfBtnClick(row)"
            >
                下架
            </el-button>
        </template>
    </SearchTable>
</template>
